import json

from django.shortcuts import render,HttpResponse,redirect
from django.views.decorators.csrf import csrf_exempt

from io import BytesIO
from app_user.utls.form import *
from app_user.utls.code import check_code, create_token, verify_token

from app_user.tasks import send_register_active_email
def login(request):
    """"""
    """登录"""
    if request.method == "GET":
        form = LoginModeForm()

        return render(request, 'login.html', {
            "form": form,
        })
    form = LoginModeForm(data=request.POST)

    if form.is_valid():
        input_code = form.cleaned_data.pop('code').upper()

        if request.session.get('image_code') != input_code:
            form.add_error('code', "验证码错误")
            return render(request, 'login.html', {
                "form": form,
            })
        user_obj = UserInfo.objects.filter(**form.cleaned_data).first()
        if not user_obj:
            form.add_error('password', "账号或密码错误")
            return render(request, 'login.html', {
                "form": form,
            })
        if user_obj.is_active == 0:
            form.add_error('name', "账户未激活！！！")
            return render(request, 'login.html', {
                "form": form,
            })

        request.session['info'] = {"id":user_obj.id, "name":user_obj.name, "level":user_obj.level, "is_active":user_obj.is_active}
        request.session.set_expiry(60 * 60 * 24)
        if user_obj.level == 1:
            return redirect('/home/')
        elif user_obj.level == 3:
            return redirect('/management/user/')
    else:
        return render(request, 'login.html', {
            "form": form,
        })



def logout(request):
    """"""
    """注销"""
    request.COOKIES.clear()
    request.session.clear()
    return redirect('/login/')

def image_code(request):
    """"""
    """生成验证码图片"""

    img, code = check_code()

    request.session['image_code'] = code

    request.session.set_expiry(60)
    stream = BytesIO()
    img.save(stream, 'png')

    return HttpResponse(stream.getvalue())



@csrf_exempt
def register(request):
    """"""
    """用户注册"""
    if request.method == "GET":
        form = RegisterModeForm()
        return render(request, "register.html", {
            "form": form,
        })
    form = RegisterModeForm(data=request.POST)
    if form.is_valid():
        user_obj = form.save(commit=False)
        user_obj.is_active = 0
        user_obj.save()
        token = create_token(user_obj.id)
        send_register_active_email.delay(user_obj.email, user_obj.name, token)
        return redirect("/login/")
    else:
        return render(request, "register.html", {
            "form": form,
        })



def user_active(reqeust, token):
    """用户激活"""
    user_id = verify_token(token)
    print(user_id)
    data = {
        "status": 0
    }
    if user_id == "Token has expired":
        data["status"] = 2
        return render(reqeust, 'user_active_status.html', context=data)
    if user_id == "Invalid token":
        data["status"] = 3
        return render(reqeust, 'user_active_status.html', context=data)
    if user_id:
        user_obj = UserInfo.objects.filter(id=user_id).first()
        if user_obj:
            user_obj.is_active = 1
            user_obj.save()
            data["status"] = 1
            return render(reqeust, 'user_active_status.html', context=data)
        else:
            data["status"] = 4
            return render(reqeust, 'user_active_status.html', context=data)
    else:
        return render(reqeust, 'user_active_status.html', context=data)

def homepage_test(request):
    """"""
    """主页测试"""

    return render(request, 'test.html')